package com.study.algorithm.day00;

import java.util.*;


public class ListByGroup {
    public static List<List<List<String>>> groupDependencies(List<List<String>> dependencies) {
        Map<String, List<List<String>>> groups = new LinkedHashMap<>();
        //遍历集合且构建分组
        for (List<String> dep : dependencies) {
            //根据版本号进行分组
            String key = dep.get(0) + dep.get(1)  + dep.get(2);
            groups.computeIfAbsent(key, k -> new ArrayList<>()).add(dep);
        }
        int maxDepth = 0;
        for (List<List<String>> versions : groups.values()) {
            if (versions.size() > maxDepth) {
                //更新深度
                maxDepth = versions.size();
            }
        }
        //构建结果
        List<List<List<String>>> result = new ArrayList<>();
        for (int i = 0; i < maxDepth; i++) {
            //一个分组
            List<List<String>> group = new ArrayList<>();
            //遍历分组后的值
            for (List<List<String>> versions : groups.values()) {
                if (i < versions.size()) {
                    //一个临时存放结果的集合
                    group.add(versions.get(i));
                }
            }
            if (!group.isEmpty()) {
                result.add(group);
            }
        }
        System.out.println(result);
        return result;
    }

    public static void main(String[] args) {
        List<List<String>> input = Arrays.asList(
                Arrays.asList("com.google.guava", "guava", "jar", "18.0"),
                Arrays.asList("com.google.guava", "guava", "jar", "17.0"),
                Arrays.asList("com.google.guava", "guava", "jar", "11.0"),
                Arrays.asList("commons-beanutils", "commons-beanutils", "jar", "1.9.2"),
                Arrays.asList("commons-beanutils", "commons-beanutils", "jar", "1.9.4"),
                Arrays.asList("commons-beanutils", "commons-beanutils", "jar", "1.9.3"),
                Arrays.asList("commons-collections", "commons-collections", "jar", "3.2.1"),
                Arrays.asList("commons-collections", "commons-collections", "jar", "3.2.2"),
                Arrays.asList("com.zaxxer", "SparseBitSet", "jar", "1.9.1")
        );

        groupDependencies(input);
    }
}
